package cn.e2win.biz.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.e2win.base.controller.MyException;
import cn.e2win.base.entity.SysFunction;
import cn.e2win.base.entity.SysRoleFunction;
import cn.e2win.base.entity.SysUser;
import cn.e2win.base.entity.SysUserRole;
import cn.e2win.biz.user.UserDao;


public class DmsUserDetailServiceImpl implements UserDetailsService {
	static Log logger = LogFactory.getLog(DmsUserDetailServiceImpl.class);

	private UserDao userDao;
	private FunctionDao functionDao;

	public UserDetails loadUserByUsername(String account)
			throws UsernameNotFoundException {
		logger.info("account is " + account);
		
		SysUser user = null;
		/*user = this.userDao.findBy("account", username).get(0);
		if (user == null) {
			throw new UsernameNotFoundException(username);
		}*/
		List<SysUser> list= userDao.getUserByAccount(account);
		if(list==null || list.size()!=1){
			throw new UsernameNotFoundException(account);
		}else{
			user = list.get(0);
		}
		Collection<DmsGrantedFunction> grantedAuths = obtionGrantedAuthorities(user);

		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		SysUser userdetail = new SysUser(user, enables, accountNonExpired,
				credentialsNonExpired, accountNonLocked, grantedAuths);
		return userdetail;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	public FunctionDao getFunctionDao() {
		return functionDao;
	}

	public void setFunctionDao(FunctionDao functionDao) {
		this.functionDao = functionDao;
	}

	// 取得用户的权限
	private Set<DmsGrantedFunction> obtionGrantedAuthorities(
			cn.e2win.base.entity.SysUser user) {
		Set<DmsGrantedFunction> authSet = new HashSet<DmsGrantedFunction>();
		
		//当多个角色拥有同一角色时，需要剔重
		Set<Integer> notRepeat = new HashSet<Integer>();
		
		//超级管理员获取所有权限
		if (user.getAccount().equals(MyUsernamePasswordAuthenticationFilter.SUPER_ADMIN_TELNO)) {
			List<SysFunction> functionList = functionDao.readAll();
			for (SysFunction fun : functionList) {
				//被逻辑删除过的
				if(fun.getActiveStatusInt() != null && fun.getActiveStatusInt().intValue() == 0){
					continue;
				}
				authSet.add(new DmsGrantedFunction(fun));
			}
		} else {
			List<SysUserRole> roles = userDao.getUserRoleListByUserId(user.getId());
			//List<SysRole> roles = user.getRoles();
			for (SysUserRole role : roles) {
				//被逻辑删除过的
				if(role.getActiveStatusInt() != null && role.getActiveStatusInt().intValue() == 0){
					continue;
				}
				//Set<SysFunction> tempFun = role.getAppliedFunctions();
				List<SysRoleFunction> tempFun = userDao.getRoleFunctionListByRoleId(role.getRoleId());
				for (SysRoleFunction fun : tempFun) {
					if (!notRepeat.contains(fun.getFunId()) && fun.getActiveStatusInt()==1){
						//authSet.add(new DmsGrantedFunction(fun));
						authSet.add(new DmsGrantedFunction((SysFunction)userDao.getEntity(SysFunction.class, fun.getFunId())));
						notRepeat.add(fun.getFunId());
					}
				}
			}
		}
		
		return authSet;
	}
}
